﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Shares.Model.Request;
using Shares.Model;
using Shares.Model.Models;
using Shares.BusinessLogic.Business;
using Shares.Core;
using System.IO;
namespace Shares.AppService
{
    public class StatisticsService
    {
        private ShareListDataBusiness shareBus = new ShareListDataBusiness();

        private HistoryDataBusiness historyBus = new HistoryDataBusiness();
        public DateTime BeginDate { get; set; }
        public DateTime EndDate { get; set; }

        private void CalculateDate(StatisticsRequest request)
        {
            DateTime endDate = DateTime.Now;
            if (endDate.DayOfWeek == DayOfWeek.Saturday || endDate.DayOfWeek == DayOfWeek.Sunday)
            {
                endDate = endDate.AddDays(-2);
            }

            DateTime beginDate = endDate.AddDays(-1 * request.SequenceDay);
            int totleWeek = request.SequenceDay / 7 + 1;
            beginDate = beginDate.AddDays(-2 * totleWeek);

            if (beginDate.DayOfWeek == DayOfWeek.Saturday || beginDate.DayOfWeek == DayOfWeek.Sunday)
            {
                beginDate = beginDate.AddDays(-2);
            }
            this.BeginDate = beginDate;
            this.EndDate = endDate;
        }

        public List<string> GetResultShares(StatisticsRequest request)
        {
            CalculateDate(request);
            List<string> shareCodes = new List<string>();
            int totalRecord = 0;
            ShareRequest shareRequest = new ShareRequest();
            shareRequest.PageSize = 100;
            var result = shareBus.GetList(shareRequest);
            totalRecord = ((PagedList<ShareList>)result).TotalItemCount;
            do
            {
                foreach (var item in result)
                {

                    if (StatisticsAnalysed(item.ShareCode, request))
                    {
                        shareCodes.Add(item.ShareCode);
                    }
                }
                shareRequest.PageIndex++;
                result = shareBus.GetList(shareRequest);
            }
            while (shareRequest.PageIndex * shareRequest.PageSize < totalRecord);

            return shareCodes;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sequenceDay"></param>
        /// <param name="type"></param>
        public void GetStatisticsData(StatisticsRequest request)
        {
            CalculateDate(request);
            string stmp = System.Reflection.Assembly.GetExecutingAssembly().Location;
            stmp = stmp.Substring(0, stmp.LastIndexOf('\\'));
            stmp = Path.Combine(stmp, "data", DateTime.Now.ToString("yyyy-MM-dd"));
            if (!Directory.Exists(stmp))
            {
                Directory.CreateDirectory(stmp);
            }
            int totalRecord = 0;
            ShareRequest shareRequest = new ShareRequest();
            shareRequest.PageSize = 100;
            var result = shareBus.GetList(shareRequest);
            totalRecord = ((PagedList<ShareList>)result).TotalItemCount;
            do
            {
                foreach (var item in result)
                {
                    LogHelper.InfoAsync("执行统计分析：" + item.ShareCode);
                    StatisticsAnalysed(item.ShareCode, stmp, request);
                }
                shareRequest.PageIndex++;
                result = shareBus.GetList(shareRequest);
            }
            while (shareRequest.PageIndex * shareRequest.PageSize < totalRecord);


        }
        /// <summary>
        /// 计算每支股票
        /// </summary>
        /// <param name="shareCode"></param>
        /// <param name="sequenceDay"></param>
        /// <param name="type"></param>
        /// <returns></returns>
        private void StatisticsAnalysed(string shareCode, string filePath, StatisticsRequest request)
        {
            HistoryRequest historyRequest = new HistoryRequest();
            historyRequest.BeginDate = this.BeginDate;
            historyRequest.EndDate = this.EndDate;
            historyRequest.ShareCode = shareCode;
            var data = historyBus.GetList(historyRequest);
            var record = data.Count();
            LogHelper.InfoAsync(string.Format("查询数据：s:{0}-e:{1},数据:{2},代码：{3}", this.BeginDate, this.EndDate, record, shareCode));

            string fileName = string.Empty;
            if (data != null && record >= 2)
            {
                var types = Enum.GetValues(typeof(AnalysedType));
                var result = false;
                foreach (var type in types)
                {
                    var t = (AnalysedType)type;
                    switch (t)
                    {
                        case AnalysedType.OpenLessThanClose:
                            result = data.All(m => m.OpenAmount <= request.GuidePrice && m.OpenAmount > 0 && m.OpenAmount < m.CloseAmout);
                            fileName = Path.Combine(filePath, "开小于收" + "_" + request.SequenceDay + ".txt");
                            break;
                        case AnalysedType.OpenMoreThanClose:
                            result = data.All(m => m.OpenAmount <= request.GuidePrice && m.OpenAmount > 0 && m.OpenAmount > m.CloseAmout);
                            fileName = Path.Combine(filePath, "开大于收" + "_" + request.SequenceDay + ".txt");
                            break;
                        case AnalysedType.SequenceDescend:
                            result = CheckIncrease(data, true, request.GuidePrice);
                            fileName = Path.Combine(filePath, "连续跌" + "_" + request.SequenceDay + ".txt");
                            break;
                        case AnalysedType.SequenceIncrease:
                            result = CheckIncrease(data, false, request.GuidePrice);
                            fileName = Path.Combine(filePath, "连续涨" + "_" + request.SequenceDay + ".txt");
                            break;
                    }
                    if (result)
                    {
                        WriteFile(fileName, shareCode);
                    }
                }
            }
            //else
            //{ 
            //   var types = Enum.GetValues(typeof(AnalysedType));
            //    foreach (var type in types)
            //    {
            //        var t = (AnalysedType)type;
            //        switch (t)
            //        {
            //            case AnalysedType.OpenLessThanClose:
            //                fileName = Path.Combine(filePath, "开小于收" +  "_" + days + ".txt");
            //                break;
            //            case AnalysedType.OpenMoreThanClose:
            //                fileName = Path.Combine(filePath,  "开大于收" + "_" + days + ".txt");
            //                break;
            //            case AnalysedType.SequenceDescend:
            //                fileName = Path.Combine(filePath, "连续跌" +  "_" + days + ".txt");
            //                break;
            //            case AnalysedType.SequenceIncrease:
            //                fileName = Path.Combine(filePath,"连续涨" +  "_" + days + ".txt");
            //                break;
            //        }
            //        WriteFile(fileName, "没有数据");
            //    }
            //}




        }
        private bool StatisticsAnalysed(string shareCode, StatisticsRequest request)
        {
            var result = false;
            HistoryRequest historyRequest = new HistoryRequest();
            historyRequest.BeginDate = this.BeginDate;
            historyRequest.EndDate = this.EndDate;
            historyRequest.ShareCode = shareCode;
            var data = historyBus.GetList(historyRequest);
            var record = data.Count();
            if (data != null && record >= 2)
            {
                switch (request.AnalysedValue)
                {
                    case AnalysedType.OpenLessThanClose:
                        result = data.All(m => m.OpenAmount <= request.GuidePrice && m.OpenAmount > 0 && m.OpenAmount < m.CloseAmout);
                        break;
                    case AnalysedType.OpenMoreThanClose:
                        result = data.All(m => m.OpenAmount <= request.GuidePrice && m.OpenAmount > 0 && m.OpenAmount > m.CloseAmout);
                        break;
                    case AnalysedType.SequenceDescend:
                        result = CheckIncrease(data, true, request.GuidePrice);

                        break;
                    case AnalysedType.SequenceIncrease:
                        result = CheckIncrease(data, false, request.GuidePrice);
                        break;
                }
            }

            return result;
        }

        /// <summary>
        /// 检测数据
        /// </summary>
        /// <param name="historyData"></param>
        /// <param name="isIncrease">是否增长</param>
        /// <returns></returns>
        private bool CheckIncrease(IEnumerable<HistoryData> historyData, bool isIncrease, decimal guidePrice)
        {
            bool result = false;
            var data = historyData.ToList();
            decimal firstClose = data.First().CloseAmout;
            if (firstClose > guidePrice || firstClose <= 0)
                return result;
            decimal tempClose = 0;
            for (var i = 1; i < data.Count; i++)
            {
                tempClose = data[i].CloseAmout;
                if (isIncrease)
                {
                    if (tempClose < firstClose)
                        return result;
                    else
                        firstClose = tempClose;
                }
                else
                {
                    if (tempClose > firstClose)
                        return result;
                    else
                        firstClose = tempClose;
                }

            }
            result = true;
            return result;
        }

        /// <summary>
        /// 写数据到文件
        /// </summary>
        /// <param name="fileName"></param>
        /// <param name="content"></param>
        private void WriteFile(string fileName, string content)
        {
            FileStream fs = new FileStream(fileName, FileMode.Append);
            StreamWriter sw = new StreamWriter(fs);
            //开始写入
            sw.WriteLine(content);
            //清空缓冲区
            sw.Flush();
            //关闭流
            sw.Close();
            fs.Close();
        }
    }
}
